package top.lshaci.learning.wechat.offiaccount.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;

import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * WechatUtil
 *
 * @author lshaci
 * @since 1.0.0
 */
public class WechatUtil {


    private static String token = "lshaci_token";

    /**
     * 1）将token、timestamp、nonce三个参数进行字典序排序
     * 2）将三个参数字符串拼接成一个字符串进行sha1加密
     * 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
     *
     * @param signature 微信加密签名
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @return 通过验证则返回true
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce) {
        String tmpStr = Stream.of(token, timestamp, nonce).sorted().collect(Collectors.joining());
        tmpStr = SecureUtil.sha1(tmpStr);
        return StrUtil.equals(tmpStr, signature);
    }
}
